package com.njupt.LinkTable;

/**
 * 24. 两两交换链表中的节点
 */
public class SwapPairs {

    public ListNode swapPairs(ListNode head) {
        //只有一个元素或者只有两个元素的情况
        if(head==null || head.next == null){
            return head;
        }

        ListNode HEAD = new ListNode(-1, head);

        ListNode p = head;
        ListNode q = head.next;
        ListNode pre = HEAD;
        ListNode rear = null;
//        ListNode next_q = null;
        while(p !=null && q != null){
            rear = q.next;
            pre.next = q;
            q.next = p;
            p.next = rear;

            pre = p;
            p = rear;

            //可能空指针异常
            if(rear == null){
                break;
            }
            q = rear.next;

        }
        return HEAD.next;
    }

    public  void printList(ListNode head){
        ListNode p = head;
        while(p != null){
            System.out.print(p.val + " ");
            p = p.next;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
//        ListNode node3 = new ListNode(4);

        head.next = node1; node1.next = node2;
//        node2.next = node3;

        SwapPairs test = new SwapPairs();
        ListNode listNode = test.swapPairs(head);
        test.printList(listNode);

    }
}
